
import XLSX from 'xlsx';
//解析excel
function parseExcel(file,callback) {   
    var f = file;
    var reader = new FileReader();
    reader.onload = function() {
      var workbook = XLSX.read(this.result, {
        type: 'buffer',
      });

      for (var sheet in workbook.Sheets) {
        if (workbook.Sheets.hasOwnProperty(sheet)) {
          callback(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
          break; 
        }
      }
    };
    reader.readAsArrayBuffer(f);
  }
  //解析csv
  function parseCSV(file,callback) {
    var that = this;
    var f =file;
    var reader = new FileReader();
    reader.onload = function() {
      var workbook = XLSX.read(this.result, {
        type: 'string',
      });

      for (var sheet in workbook.Sheets) {
        if (workbook.Sheets.hasOwnProperty(sheet)) {
          callback(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
          break;
        }
      }
    };
    reader.readAsText(f);
  }
  //获取数组
  function getArray(obj) {
    for (var i in obj) {
      var val = obj[i];
      if (val instanceof Array) {
        return val;
      } else if (val instanceof Object) {
        getArray(val);
      }
    }
    
  }
//从对象获取数组
var arrayFromObj={
  getArray:function(obj) {
      for (var i in obj) {
        var val = obj[i];
        if (val instanceof Array) {
          this.result=val ;
        } else if (val instanceof Object) {
          this.getArray(val);
        }
      }                
    },
    data:{},
    result:[]
};
  //解析json
 function  parseJSON(file,callback) {
    
    var f =file;
    var reader = new FileReader();
    reader.onload = function() {
        var r=this.result;
        
        arrayFromObj.data = JSON.parse(r);
      if ( arrayFromObj.data instanceof Array) {
        callback( arrayFromObj.data);
      } else if ( arrayFromObj.data instanceof Object) {
        arrayFromObj.getArray( arrayFromObj.data);
        callback(arrayFromObj.result);
      }
    };
    reader.readAsText(f);
  }
//获取文件类型
  function getFileType(file){
    var fileName=file.name;
    var ex=fileName.substring(fileName.lastIndexOf('.') + 1);
    if (ex == 'xls' || ex == 'xlsx') {
        return 'EXCEL';
      } else if (ex == 'json') {
        return 'JSON';
      } else if (ex == 'csv') {
        return 'CSV';
      }   
      return 'ERROR';
  }
//解析文件
function parseFile(file,callback){
    var fileName=file.name;
    var ex=fileName.substring(fileName.lastIndexOf('.') + 1);
    if (ex == 'xls' || ex == 'xlsx') {
        parseExcel(file,callback);
        return 'EXCEL';
      } else if (ex == 'json') {
        parseJSON(file,callback);
        return 'JSON';
      } else if (ex == 'csv') {
        parseCSV(file,callback);
        return 'CSV';
      }   
      return 'ERROR'; 

}
export default {parseFile,arrayFromObj,getFileType,getArray};